package priv.happy.mealpickpro.log;

import cn.hutool.core.date.DateUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import priv.happy.mealpickpro.domain.LoginLog;
import priv.happy.mealpickpro.service.LoginLogService;
import priv.happy.mealpickpro.vo.UserVO;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
import java.util.StringTokenizer;

/**
 * @Author: HAPPY
 * @Project_name: mealPickPro
 * @Package_name: priv.happy.mealpickpro.log
 * @Date: 2023/10/21 16:06
 * @Description:
 */
@Component
@Aspect
public class LoginLogAspect {
    @Autowired
    LoginLogService loginLogService;

    @Around(value = "execution(* priv.happy.mealpickpro.service.impl.AuthenticationServiceImpl.login(..))")
    public Object loginLog(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        UserVO result = null;
        //获取request
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String remoteHost = request.getRemoteHost();

        String userAgent = request.getHeader("User-Agent");
        StringTokenizer st = new StringTokenizer(userAgent, ";");

        //得到用户的浏览器名
        String userBrowser = st.nextToken();
        //得到用户的操作系统名
        String userOS = st.nextToken();
        LoginLog loginLog = new LoginLog();
        loginLog.setLoginTime(DateUtil.now())
                .setClient(userOS + " : " + userBrowser + ")").setIp(remoteHost);
        try {
            // 得到执行结果，是一个FoodVO
            result = (UserVO) proceedingJoinPoint.proceed();
            loginLog.setUserId(result.getUserMeal().getId()).setUserName(result.getUserMeal().getName());
            if (result.getUserMeal().getId() != null) {
                new DateUtil();
                loginLog.setResult("登录成功");
            } else {
                loginLog.setResult("登录失败");
            }
            loginLogService.save(loginLog);
        } catch (Exception e) {
            loginLog.setResult("登录失败:" + e.getMessage());
        }

        return result;
    }
}
